package com.example.sprinbgbatch.config;

import com.example.sprinbgbatch.config.listener.MyChunkListener;
import com.example.sprinbgbatch.config.listener.MyJobListener;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.support.ListItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;

//@Configuration
public class ListenerDemo {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;
    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    public Step step1(){
        return stepBuilderFactory.get("step1")
                .<String,String>chunk(2)  //每读两个数据就进行相应的处理
                .faultTolerant()                   //容错
                .listener(new MyChunkListener())
                .reader(reader())
                .writer(writer())
                .build();
    }

    private ItemReader<? extends String> reader() {
        return new ListItemReader<>(Arrays.asList("张三","李四","王五","赵六","洪七"));
    }

    private ItemWriter<? super String> writer() {
        return new ItemWriter<String>() {

            @Override
            public void write(List<? extends String> items) throws Exception {
                for(String item:items) {
                    System.out.println("Writing item: "+item);
                }

            }
        };
    }

    //监听Job执行
    @Bean
    public Job myListenerDemo() {
        return jobBuilderFactory.get("myListenerDemo")
                .start(step1())
                .listener(new MyJobListener())
                .build();

    }



}
